import { generateId } from '@/util/utils';
import { cloneDeep } from 'lodash';
import { useMemo } from 'react';
import { DragDropContext } from 'react-beautiful-dnd';
import DraggableTpl from './components/DraggableTpl';
import type { Dispatch } from '@umijs/max';
import { connect } from '@umijs/max';
import { Button, message } from 'antd';
import type { draggableAPI } from '@/models/models';
import styles from './index.less';

interface IProps extends draggableAPI.IState {
  dispatch: Dispatch;
}

function CurrentCase(props: IProps) {
  const { dispatch, leftLists, moduleFloorList } = props;

  const handleDispatch = (payload: { moduleFloorList: draggableAPI.IState['moduleFloorList'] }) => {
    dispatch({
      type: 'draggableModel/save',
      payload: {
        ...payload,
      },
    });
  };

  const reorder = (
    list: draggableAPI.IState['moduleFloorList'] | draggableAPI.moduleItem[],
    startIndex: number,
    endIndex: number,
  ) => {
    console.log('list', list, startIndex, endIndex);
    const result = list;
    const [removed] = result.splice(startIndex, 1);
    console.log('recorder', list, result, removed, [removed]);
    result.splice(endIndex, 0, removed as draggableAPI.moduleItem);

    return result;
  };

  const onDragEnd = (result: any) => {
    const { source, destination, draggableId } = result;
    let newModuleFloorList = cloneDeep(moduleFloorList);

    // dropped outside the list
    if (!destination) {
      return;
    }
    const sInd = source.droppableId;
    const dInd = destination.droppableId;

    console.log('onDragEnd function', result, sInd, dInd);

    // 拖拽进右侧区域（非楼层区域）
    if (sInd !== 'rightArea' && dInd === 'rightArea') {
      message.error('模块只能添加进楼层区域！');
      return;
    }

    // 拖拽进楼层区
    if (dInd !== 'leftArea' && dInd !== 'rightArea') {
      if (sInd === 'leftArea') {
        newModuleFloorList.forEach((floorItem) => {
          if (floorItem.id === dInd) {
            // 在 leftLists 中查找，拖拽的 item, 不能修改 leftLists 中的 module id
            const [addModuleItem] = cloneDeep(leftLists).filter((item) => item.id === draggableId);
            // ! DragDropContext 下 id 不能重复，如果重复，leftArea 的 module 不能重复使用
            addModuleItem.id = addModuleItem.id + `_${dInd}_${generateId()}`;
            // 添加到对应的楼层
            floorItem.moduleList.splice(destination.index, 0, addModuleItem);
          }
        });
      } else if (sInd !== 'rightArea' && sInd !== 'leftArea') {
        if (sInd === dInd) {
          // 同楼层交换
          const curFloor = newModuleFloorList.filter((floor) => floor.id === sInd);
          const newModuleList = reorder(curFloor[0].moduleList, source.index, destination.index);
          console.log('curFloor', curFloor, newModuleList);

          curFloor[0].moduleList = newModuleList as draggableAPI.moduleItem[];
        }
      }
    } else if (sInd === 'rightArea' && dInd === 'rightArea') {
      // 楼层交换
      newModuleFloorList = reorder(
        newModuleFloorList,
        source.index,
        destination.index,
      ) as draggableAPI.IState['moduleFloorList'];
    }

    console.log('newModuleFloorList', newModuleFloorList);
    handleDispatch({ moduleFloorList: newModuleFloorList });
  };

  const moduleFloorListWidthDel = useMemo(() => {
    return moduleFloorList.map((floor) => {
      return {
        ...floor,
        // draggableAreaStyle:{ marginLeft: 12, background: 'red' },
        onDelete: (floorItemIndex: number) => {
          const newState = [...moduleFloorList];
          newState.splice(floorItemIndex, 1);
          handleDispatch({ moduleFloorList: newState });
        },
        moduleList: floor.moduleList.map((module) => {
          return {
            ...module,
            onDelete: (moduleItemIndex: number, floorItem: draggableAPI.moduleItem) => {
              const newState = [...moduleFloorList];
              // eslint-disable-next-line @typescript-eslint/no-shadow
              const curFloorModules = newState.filter((module) => module.id === floorItem.id);
              curFloorModules[0]?.moduleList?.splice(moduleItemIndex, 1);
              handleDispatch({ moduleFloorList: newState });
            },
          };
        }),
      };
    });
  }, [moduleFloorList]);

  const leftAreaOptions = {
    droppableId: 'leftArea',
    draggableAreaStyle: {},
    draggableAreaItemStyle: {},
    draggableAreaDataList: leftLists,
  };

  const rightAreaOptions = {
    droppableId: 'rightArea',
    draggableAreaStyle: { width: 20 },
    draggableAreaItemStyle: { width: 320 },
    draggableAreaDataList: moduleFloorListWidthDel,
  };

  // 新增楼层
  const handleAddFloor = () => {
    const newModuleFloorList = [
      ...moduleFloorList,
      {
        id: generateId(),
        moduleList: [],
      },
    ];
    handleDispatch({ moduleFloorList: newModuleFloorList });
  };

  return (
    <div className={styles.draggableContainer}>
      <DragDropContext onDragEnd={onDragEnd}>
        <DraggableTpl {...leftAreaOptions} />
        <div className={styles.rightBox}>
          <DraggableTpl {...rightAreaOptions} />
          <Button type="primary" className={styles.addBtn} onClick={handleAddFloor}>
            新增楼层
          </Button>
        </div>
      </DragDropContext>
    </div>
  );
}

export default connect(({ draggableModel }: { draggableModel: draggableAPI.IState }) => {
  return {
    leftLists: draggableModel.leftLists,
    moduleFloorList: draggableModel.moduleFloorList,
  };
})(CurrentCase);
